import sys, time, hashlib, base64, requests
from jinja2 import Environment, FileSystemLoader
from selenium import webdriver
from collections import defaultdict

def html_set_data(texdata, outprefix):
    path_dir = '/' + '/'.join(outprefix.split('/')[1:-1])
    env = Environment(loader=FileSystemLoader('/home/yong_sun/bin/workflow/qcstat/'))
    template = env.get_template('tempQC.html')
    buf = template.render(texdata)
    html = f'{outprefix}.fastq.Stats.html'
    with open(html, "w", encoding="utf-8") as fp:
        fp.write(buf)
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-gpu')
    chrome_options.add_argument('--disable-dev-shm-usage')
    browser = webdriver.Chrome(options=chrome_options)
    browser.get(f'file://{html}')
    time.sleep(3)
    browser.quit()

    try:
        url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=c635edcf-1adb-4277-9152-060d661c20b7'
        name = outprefix.split('/')[-1]
        requests.post(url, json={"msgtype": "text", "text": {"content": f"{name}"}})
        with open('fastq.stats.png', 'rb') as fq:
            png = fq.read()
            md5 = hashlib.md5(png).hexdigest()
            b64 = base64.b64encode(png).decode('utf-8')
            data = {'msgtype': 'image','image': {'base64': b64,'md5': md5}}
            requests.post(url, json=data)
    except Exception as e:
        print(e)
        sys.exit('PNG is not exists!')


with open(sys.argv[1]) as csv, open(sys.argv[2]) as stat, open(sys.argv[3]+'.fastq.Stats.xls', 'w') as out:
    flag = 0
    sample = {}
    for i in csv:
        if flag == 0:
            if i.startswith('Sample_ID'):
                flag = 1
            else:
                continue
            continue
        if flag == 1:
            x = i.split(',')
            sample[f'Barcode{x[4]}'] = x[0]
    stat.readline()
    outdata = {'tabledata1': []}
    outdata['tabledata1'].append({'sampleID': 'sampleID', 'tindex': 'index', 'treadsNumber': 'readsNumber'})

    out.write('sampleID\tindex\treadsNumber\n')
    for i in stat:
        x = i.strip().split('\t')
        if x[0].find('otherindex') > -1:
            out.write(f'{x[0]}\t{x[0]}\t{int(x[1]):,}\n')
            outdata['tabledata1'].append({'sampleID': f'{x[0]}', 'tindex': f'{x[0]}', 'treadsNumber': f'{int(x[1]):,}'})
        elif x[0].find('undecoded') > -1:
            out.write(f'{x[0]}\t{x[0]}\t{int(x[1]):,}\n')
            outdata['tabledata1'].append({'sampleID': f'{x[0]}', 'tindex': f'{x[0]}', 'treadsNumber': f'{int(x[1]):,}'})
        elif x[0] == 'TotalReads':
            out.write(f'{x[0]}\t{x[0]}\t{int(x[1]):,}\n')
            outdata['tabledata1'].append({'sampleID': f'{x[0]}', 'tindex': f'{x[0]}', 'treadsNumber': f'{int(x[1]):,}'})
        else:
            if int(x[1]) > 15000000 or sample[x[0]].startswith('NC') or sample[x[0]].find('YF') > -1 or sample[x[0]].find('KY') > -1 or sample[x[0]].find('SY') > -1:
                bit15M = False
            else:
                bit15M = True
            out.write(f'{sample[x[0]]}\t{x[0]}\t{int(x[1]):,}\n')
            outdata['tabledata1'].append({'sampleID': sample[x[0]], 'tindex': x[0], 'treadsNumber': f'{int(x[1]):,}', 'bit15M': bit15M})

    html_set_data(outdata, sys.argv[3])
